package io.dcloud.uniplugin;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;
import io.dcloud.uniplugin.bean.MessageEvent;
import io.dcloud.uniplugin.tools.ThreadTools;

/**
 * author : yzhg
 * 包名: com.benben.nfc_lib
 * 时间: 2024-09-06 11:21
 * 描述：
 *
 */
public class NFCModel extends UniModule {

    /*保存一个Activity*/
    public static List<Activity> list = new ArrayList<>();


    public static int REQUEST_CODE = 1000;
    private static UniJSCallback callback;


    private static UniJSCallback setCallback;

    /*读取工厂端还是用户端数据*/
    public static boolean isFactory = false;


    /*密码 - 是否使用默认密码*/
    public static boolean isDefaultPassword = true;

    /*读取成功*/
    public static final String INIT_SUCCESS = "201";
    /*读取成功*/
    public static final String RED_SUCCESS = "202";
    /*写入成功*/
    public static final String WRITE_SUCCESS = "203";

    /**
     * 回调数据
     */
    public static void invokeSuccess(JSONObject jsonObject) {
        ThreadTools.runOnMainThread(() -> {
            jsonObject.put("status", "success");
            jsonObject.put("message", "success");
            callback.invokeAndKeepAlive(jsonObject);
        });
    }

    public static void invokeSuccess(String message) {
        ThreadTools.runOnMainThread(() -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", "success");
            jsonObject.put("message", message);
            callback.invokeAndKeepAlive(jsonObject);
        });
    }

    public static void invokeSuccess(String message, String status) {
        ThreadTools.runOnMainThread(() -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", status);
            jsonObject.put("message", message);
            callback.invokeAndKeepAlive(jsonObject);
        });
    }

    /**
     * 回调失败
     */
    public static void invokeError(String errorMessage) {
        ThreadTools.runOnMainThread(() -> {
            JSONObject data = new JSONObject();
            data.put("status", "error");
            data.put("message", errorMessage);
            callback.invokeAndKeepAlive(data);
        });
    }

    public static void invokeError(String errorMessage, String code) {
        ThreadTools.runOnMainThread(() -> {
            JSONObject data = new JSONObject();
            data.put("status", "error");
            data.put("message", errorMessage);
            data.put("code", code);
            callback.invokeAndKeepAlive(data);
        });
    }

    /**
     * 回调数据
     */
    public static void invokeWriteSuccess(JSONObject jsonObject) {
        jsonObject.put("status", "success");
        jsonObject.put("message", "success");
        Log.i("invokeSuccessinvokeSuccess", "invokeSuccess: " + jsonObject.toJSONString());
        setCallback.invokeAndKeepAlive(jsonObject);
    }

    public static void invokeWriteSuccess(String message) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", "success");
        jsonObject.put("message", message);
        setCallback.invokeAndKeepAlive(jsonObject);
    }

    /**
     * 回调失败
     */
    public static void invokeWriteError(String errorMessage) {
        JSONObject data = new JSONObject();
        data.put("status", "error");
        data.put("message", errorMessage);
        setCallback.invokeAndKeepAlive(data);
    }

    /**
     * isFactory 是否工厂端  false用户端 true是 工厂端 （非工厂端 弹弹框）
     * @param options
     * @param callback
     */
    //run ui thread
    @UniJSMethod(uiThread = true)
    public void testAsyncFunc(JSONObject options, UniJSCallback callback) {
        this.callback = callback;
        if (callback != null) {
            if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
                Intent intent = new Intent(mUniSDKInstance.getContext(), NFCHomeActivity.class);
                intent.putExtra("isFactory", false);
                intent.putExtra("data", com.alibaba.fastjson.JSON.toJSONString(options));
                ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
            }
        }
    }

    @UniJSMethod(uiThread = true)
    public void testAsyncFunc2(JSONObject options, UniJSCallback callback) {
        this.callback = callback;
        if (callback != null) {
            if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
                Intent intent = new Intent(mUniSDKInstance.getContext(), NFCHomeActivity.class);
                intent.putExtra("isFactory", true);
                intent.putExtra("data", com.alibaba.fastjson.JSON.toJSONString(options));
                ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
            }
        }
    }


    /**
     * 设置是否使用默认秘钥
     */
    @UniJSMethod(uiThread = true)
    public void useDefaultPas(JSONObject options,UniJSCallback callback) {
        isDefaultPassword = true;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", "success");
        jsonObject.put("message", "切换成功:使用默认秘钥");
        callback.invokeAndKeepAlive(jsonObject);
    }


    @UniJSMethod(uiThread = true)
    public void noUseDefaultPas(JSONObject options,UniJSCallback callback) {
        isDefaultPassword = false;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", "success");
        jsonObject.put("message", "切换成功:使用正式秘钥");
        callback.invokeAndKeepAlive(jsonObject);
    }


    @UniJSMethod(uiThread = true)
    public void testAsyncFunc3(JSONObject options, UniJSCallback callback) {
        this.callback = callback;
        if (callback != null) {
            if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
                Intent intent = new Intent(mUniSDKInstance.getContext(), NFCHomeActivity.class);
                intent.putExtra("isFactory", true);
                intent.putExtra("data", com.alibaba.fastjson.JSON.toJSONString(options));
                intent.putExtra("isDefaultPassword", true);
                ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
            }
        }
    }

    @UniJSMethod(uiThread = true)
    public void writeFunc3(JSONObject jsonObject, UniJSCallback callback) {
        this.callback = callback;
        if (jsonObject != null) {
            EventBus.getDefault().post(new MessageEvent<Object>(MessageEvent.WRITE_MESSAGE, jsonObject));
        } else {
            invokeError("写入失败！NFC未初始化");
        }
    }

    /**
     * 用户端的写入 需要弹框
     * @param jsonObject
     * @param callback
     */
    @UniJSMethod(uiThread = true)
    public void writeFunc(JSONObject jsonObject, UniJSCallback callback) {
        this.callback = callback;
        if (callback != null && jsonObject != null) {
            if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
                Intent intent = new Intent(mUniSDKInstance.getContext(), NFCHomeActivity.class);
                intent.putExtra("isFactory", false);
                intent.putExtra("isWrite", true);
                intent.putExtra("data", com.alibaba.fastjson.JSON.toJSONString(jsonObject));
                ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
            }
        } else {
            invokeError("写入失败！NFC未初始化");
        }
    }

    /**
     * 工厂端的写入 需要弹框
     * @param jsonObject
     * @param callback
     */
    @UniJSMethod(uiThread = true)
    public void writeFunc2(JSONObject jsonObject, UniJSCallback callback) {
        this.callback = callback;
        if (callback != null && jsonObject != null) {
            if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
                Intent intent = new Intent(mUniSDKInstance.getContext(), NFCHomeActivity.class);
                intent.putExtra("isFactory", true);
                intent.putExtra("isWrite", true);
                intent.putExtra("data", com.alibaba.fastjson.JSON.toJSONString(jsonObject));
                ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
            }
        } else {
            invokeError("写入失败！NFC未初始化");
        }
    }

    /**
     * 页面关闭
     */
    @UniJSMethod(uiThread = true)
    public void closeNfcActivity(UniJSCallback callback) {
        if (!list.isEmpty()) {
            for (Activity activity : list) {
                activity.finish();
            }
        }
        callback.invoke("关闭成功");
    }


    @UniJSMethod(uiThread = true)
    public void gotoNativePage(JSONObject options, UniJSCallback callback) {
        if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
            Intent intent = new Intent(mUniSDKInstance.getContext(), NFCHomeActivity.class);
            intent.putExtra("isFactory", false);
            ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
        }
    }

    @UniJSMethod(uiThread = true)
    public void gotoNativePage2(JSONObject options, UniJSCallback callback) {
        if (mUniSDKInstance != null && mUniSDKInstance.getContext() instanceof Activity) {
            Intent intent = new Intent(mUniSDKInstance.getContext(), NFCHomeActivity.class);
            intent.putExtra("isFactory", true);
            ((Activity) mUniSDKInstance.getContext()).startActivityForResult(intent, REQUEST_CODE);
        }
    }
}
